package com.wenlin.myproduction.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.wenlin.myproduction.R;
import com.wenlin.myproduction.util.Checker;
import com.wenlin.myproduction.util.TypeData;
import com.wenlin.myproduction.util.TypeDataNames;
import com.wenlin.myproduction.util.UI;
import com.wenlin.myproduction.util.ValCommon;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;

/**
 * @author 文琳_377979485@qq.com
 * @time 2021/9/2 0002 下午 5:57
 * @desc 输入内容延迟一段时间后再触发动作的输入框控件
 */
@SuppressLint("AppCompatCustomView")
public class AutoSearchEtLayout extends ConstraintLayout {
    private static final int HANDLE_SEARCH = 1;
    private final MyHandler handler = new MyHandler(this);
    private AutoSearch autoSearch;

    private EditText et;
    private ImageView iv;

    public AutoSearchEtLayout(Context context) {
        super(context, null);
    }

    public AutoSearchEtLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = LayoutInflater.from(context).inflate(R.layout.layout_auto_search_et, this, true);
        et = view.findViewById(R.id.et_search);
        iv = view.findViewById(R.id.iv);
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    /**
     * 初始化
     * @param strResId 提示文本资源编号
     * @param autoSearch 自动搜素接口
     */
    public void init(int strResId, AutoSearch autoSearch) {
        String str = UI.getStr(strResId);
        init(str, autoSearch);
    }

    /**
     * 初始化
     * @param hint 提示文本
     * @param autoSearch 自动搜索接口
     */
    public void init(String hint, AutoSearch autoSearch) {
        this.autoSearch = autoSearch;
        if (Checker.hasNoWord(hint)) hint = UI.getStr(R.string.input_keyword);
        et.setHint(hint);
        if (Checker.notNull(et)) {
            et.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    String str = s.toString();
                    Message msg = Message.obtain();
                    msg.what = HANDLE_SEARCH;
                    msg.obj = str;
                    handler.sendMessageDelayed(msg, ValCommon.ET_DELAY_TO_SEARCH);
                }
            });
            et.setOnEditorActionListener((v, actionId, event) -> {
                if (null != autoSearch) autoSearch.onSearch();
                return true;
            });
        }
        if (Checker.notNull(iv)) {
            iv.setOnClickListener(v -> {
                if (null != autoSearch) autoSearch.onSearch();
            });
        }
    }

    public EditText getEt() {
        return et;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void threadHandle(TypeData typeData) {
        String name = typeData.getName();
        if (name.equals(TypeDataNames.toSearch)) {
            int id = (int) typeData.getData();
            if (getId() != id) return;
            if (null != autoSearch) autoSearch.onSearch();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        UI.releaseHandler(handler);
//        KeyboardUtils.hideSoftInput(this);//好像没作用
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
        super.onDetachedFromWindow();
    }

    private static class MyHandler extends Handler {
        private final WeakReference<AutoSearchEtLayout> autoSearchEtWeakReference;

        MyHandler(AutoSearchEtLayout et) {
            autoSearchEtWeakReference = new WeakReference<>(et);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            AutoSearchEtLayout layout = autoSearchEtWeakReference.get();
            if (layout == null) return;
            if (msg.what == HANDLE_SEARCH) {
                String searchStr = msg.obj.toString();
                if (searchStr.equals(layout.et.getText().toString().trim())) {//说明等了500毫秒之后没有输入新内容
                    EventBus.getDefault().post(new TypeData<>(TypeDataNames.toSearch, layout.getId()));
                }
            }
        }
    }

    public interface AutoSearch {
        void onSearch();//根据输入的关键字去通过数据接口获取数据
    }
}
